<BS># Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head) :
        prev = None
        while head :
            next = head.next
            head.next = prev
            prev = head
            head = next
        return prev

    def reverseKGroup(self, head, k):
        newHead = ListNode(0, head)
        begin = newHead.next
        end = newHead
        prev = newHead
        while begin :
            for i in range(k) :
                if not end : break
                end = end.next
            if not end : break

            next = end.next
            end.next = None
            prev.next = self.reverseList(begin)
            begin.next = next

            prev = begin
            end = begin
            begin = next
        return newHead.next




